package controller;

import controller.util.PaginationHelper;
import facade.AbstractFacade;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;

/**
 * PaginationController
 *
 * Abstract class providing pagination capabilities for model listings.
 */
public abstract class PaginationController {

    protected PaginationHelper pagination;

    abstract AbstractFacade getFacade();

    public PaginationController() {
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(15) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public DataModel getItems() {
        return getPagination().createPageDataModel();
    }

    private void recreatePagination() {
        pagination = null;
    }

    public String next() {
        getPagination().nextPage();
        return "";
    }

    public String previous() {
        getPagination().previousPage();
        return "";
    }
}
